﻿using HMACAuthentication.WebApi.Filters;
using YMJF_Service.Common;
using YMJF_Service.Models;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace YMJF_Service.Controllers
{
    /// <summary>
    /// 在线报名
    /// </summary>
    [RoutePrefix("api/apply")]
    public class ApplyController : ApiController
    {
        ConnectionStringMySQLDB db = new ConnectionStringMySQLDB();
        MemoryCacher mc = new MemoryCacher();

        public class Stat
        {
            public string Status { get; set; }
            public int Num { get; set; }
        }

        /// <summary>
        /// 获取申请信息列表
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pagesize">每页行数</param>
        /// <param name="sort">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <param name="name">用户名称</param>
        /// <param name="state">表单状态</param>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        [HMACAuthenticationAttribute]
        public ApiResult GetList(long page, long pagesize, string sort, string order, string name,string state)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sqlwhere = "";
                if (!string.IsNullOrEmpty(name))
                {
                    sqlwhere += string.Format(" and e.Name like '%{0}%' ", name);
                }
                if (!string.IsNullOrEmpty(state))
                {
                    sqlwhere += string.Format(" and e.State='{0}' ", state);
                }
                string sqlorder = " order by " + sort + " " + order;
                Page<apply> list = apply.Page(page, pagesize, @" select * from ( 	SELECT	e.ID,e.Name,e.Phone,e.Email,e.Age,d1.ItemName as Province,e.CityProper,d2.ItemName as Brand,
			                                                            d3.ItemName as Models,e.BuyTime,d4.ItemName as State,e.Remark,e.SysOrder,e.SysCreatedBy,e.SysCreate,
			                                                            e.SysLastUpdBy,e.SysLastUpd,e.SysDeleted
	                                                                   FROM apply e  left join dictionarydetail d1 on d1.ItemCode = e.Province and d1.DictCode = 'Province'
			                                                             left join dictionarydetail d2 on d2.ItemCode = e.Brand and d2.DictCode = 'Brand'
			                                                             left join dictionarydetail d3 on d3.ItemCode = e.Models and d3.DictCode = 'Models'
                                                                         left join dictionarydetail d4 on d4.ItemCode = e.State and d4.DictCode = 'ApplyState'
			                                                             where e.SysDeleted = 0  " + sqlwhere + " ) t " + sqlorder);
                res.code = HttpCode.success;
                res.message = "获取列表成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("apply", "获取申请信息列表错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        public class applys : apply
        {
            public string vcode { get; set; }
        }

        /// <summary>
        /// 提交申请表单（前端）
        /// </summary>
        /// <param name="data">申请表单信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("add")]
        public ApiResult Addapply(applys datas)
        {
            ApiResult res = new ApiResult();
            try
            {
                //暂时没用验证码
               // if (mc.Contains(datas.vcode))
                //{
                    //mc.Delete(datas.vcode);
                    apply data = (apply)datas;
                    string user = "admin";
                    data.ID = Guid.NewGuid().ToString();
                    data.State = "apply"; //申请中
                    data.SysOrder = 9999;
                    data.SysCreatedBy = user;
                    data.SysCreate = DateTime.Now;
                    data.SysLastUpdBy = user;
                    data.SysLastUpd = DateTime.Now;
                    data.SysDeleted = false;
                    object obj = data.Insert();
                    if (obj != null)
                    {
                        res.code = HttpCode.success;
                        res.message = "添加成功";
                    }
                    else
                    {
                        res.code = HttpCode.Add_Failed;
                        res.message = "添加失败";
                    }
                //}
                //else
                //{
                //    res.code = HttpCode.Add_Failed;
                //    res.message = "验证码不正确";
                //}

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("apply", "提交表单（前端）错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 修改表单状态
        /// </summary>
        /// <param name="data">申请表单信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("state/update")]
        [HMACAuthenticationAttribute]
        public ApiResult UpdateApplyState(apply data)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";
                apply apply1 = apply.SingleOrDefault(" where ID = @0 ", data.ID);
                apply1.State = data.State;
                apply1.SysLastUpd = DateTime.Now;
                apply1.SysLastUpdBy = user;

                int obj = apply1.Update();

                if (obj > 0)
                {
                    res.code = HttpCode.success;
                    res.message = "处理成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "处理失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("apply", "修改申请表单状态错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }


        /// <summary>
        /// 删除申请表单
        /// </summary>
        /// <param name="ID">申请表单信息ID</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("del")]
        [HMACAuthenticationAttribute]
        public ApiResult DelApply(string ID)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";
                int obj = apply.Update(string.Format(" set SysDeleted = 1,SysLastUpd = '{1}',SysLastUpdBy = '{2}' where ID = '{0}' ", ID, DateTime.Now, user));
                if (obj > 0)
                {
                    res.code = HttpCode.success;
                    res.message = "删除成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "删除失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("apply", "删除申请表单错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

        /// <summary>
        ///  删除申请表单(批量)
        /// </summary>
        /// <param name="data">申请表单信息ID列表</param>
        /// <returns></returns>
        [HttpPost]
        [Route("del2")]
        [HMACAuthenticationAttribute]
        public ApiResult DelApply2(List<string> data)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";
                int obj = 0;
                foreach (var ID in data)
                {
                    string sql = string.Format(" set SysDeleted = 1, SysLastUpd = '{1}', SysLastUpdBy = '{2}' where ID = '{0}' ", ID, DateTime.Now, user);
                    obj += apply.Update(sql);
                }

                if (obj==data.Count)
                {
                    res.code = HttpCode.success;
                    res.message = "删除成功";
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "删除失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL("apply", "删除申请表单(批量)错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }


    }
}